package com.ctshk.app.order.goods.config;

import com.ctshk.common.model.AppReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class WebAspect {

    @Pointcut("execution(public * com.ctshk.app.order.goods.controller..*.*(..))") //切入点
    public void controllerAop() {
    }

    /**
     * 定义环绕增强
     */
    @Around("controllerAop()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取入参
        Object[] args = joinPoint.getArgs();

        if (ArrayUtils.isNotEmpty(args)) {
            for (Object arg : args) {
                if (arg instanceof AppReq) {
                    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                    // 获取headers
                    String channel = request.getHeader("channel");
                    String os = request.getHeader("os");
                    String ct = request.getHeader("ct");
                    // 对入参进行处理
                    AppReq appReq = (AppReq) arg;
                    appReq.setProperties(channel, os, ct);

                }
            }
        }
        return joinPoint.proceed(args);
    }
}
